<template>
    <div>
        <Button @click="addUser">添加用户数据</Button>

        <Button @click="cuts">删除用户数据</Button>

         <Input placeholder="Enter text" style="width: auto" :search="true" @on-search="search">
            <Icon type="ios-search"  slot="suffix" style="cursor:pointer"/>
        </Input>
        <Table border :columns="columns" :data="list" ref="selection" @on-selection-change="getSelections">
            <template slot-scope="{ row }" slot="name">
                <strong>{{ row.name }}</strong>
            </template>
            <template slot-scope="{ row }" slot="action">
                <Button type="primary" size="small" style="margin-right: 5px" @click="show(row._id)">修改</Button>
                <Button type="error" size="small" @click="remove(row._id)">删除</Button>
            </template>
        </Table>
        <Modal title = "用户信息" v-model = "modal8" :mask-closable = "false" :footer-hide="true" :scrollable="true" :draggable="true" >
            <i slot="close" @click="close('formValidate')">
                <Icon type="ios-close" size="32"/>
            </i>
            <template>
                <Form ref="formValidate" :model="formValidate" :rules="ruleValidate" :label-width="80">
                    <FormItem label="用户名:" prop="name">
                        <Input v-model="formValidate.name" placeholder="请输入用户名..."></Input>
                    </FormItem>
                    <FormItem label="密码:" prop="password">
                        <Input type="password" v-model="formValidate.password"></Input>
                    </FormItem>
                    <FormItem label="婚姻状况" prop="marital">
                        <Select v-model="formValidate.marital" placeholder="婚姻状况">
                            <Option value="未婚">未婚</Option>
                            <Option value="已婚">已婚</Option>
                            <Option value="丧偶">丧偶</Option>
                        </Select>
                    </FormItem>
                    <FormItem label="出生日期">
                        <Row>
                            <Col span="11">
                                <FormItem prop="birth">
                                    <DatePicker type="date" placeholder="请选择出生年月"
                                    v-model = "formValidate.birth" @on-change = "setAge" :editable = "false"></DatePicker>
                                </FormItem>
                            </Col>
                        </Row>
                    </FormItem>
                    <FormItem label="年龄:" prop="age">
                        <Input v-model="formValidate.age" :number="true" :readonly = "true"></Input>
                    </FormItem>
                    <FormItem label="性别" prop="gender">
                        <RadioGroup v-model="formValidate.gender">
                            <Radio label="男">男</Radio>
                            <Radio label="女">女</Radio>
                        </RadioGroup>
                    </FormItem>
                    <FormItem label="月收入:" prop="salary">
                        <Input v-model="formValidate.salary" prefix="logo-yen" placeholder="用户月收入" style="width: 120px"/>
                    </FormItem>

                    <FormItem label="个人爱好" prop="hobby">
                        <CheckboxGroup v-model="formValidate.hobby">
                            <Checkbox label="军事"></Checkbox>
                            <Checkbox label="艺术"></Checkbox>
                            <Checkbox label="体育"></Checkbox>
                            <Checkbox label="文学"></Checkbox>
                            <Checkbox label="时政"></Checkbox>
                            <Checkbox label="历史"></Checkbox>
                            <Checkbox label="其他"></Checkbox>
                        </CheckboxGroup>
                    </FormItem>
                    <FormItem label="用户备注" prop="desc">
                        <Input v-model="formValidate.desc" type="textarea" :autosize="{minRows: 2,maxRows: 5}" placeholder="请输入用户备注说明..."></Input>
                    </FormItem>
                    <FormItem>
                        <Button type="primary" @click="handleSubmit('formValidate')">提交</Button>
                        <Button @click="handleReset('formValidate')" style="margin-left: 8px">重置</Button>
                    </FormItem>
                </Form>
            </template>
        </Modal>
        <Page :total="total" show-sizer @on-change="onChangePage" :page-size-opts="[5,10,15,20]" :page-size="rows" @on-page-size-change="onPageSizeChange"/>
    </div>
</template>
<script>
    let moment = require('moment');
    export default {
        data () {
            const validate=(rule,value,callback)=>{
                if(typeof(value)=="object"||typeof(value=="string")||typeof(value)=="number"){
                    callback()
                }else{
                    callback(new Error('数据类型错误'))
                }
            };
            return {
                columns: [
                    {
                        type : 'selection',
                        width: 60,
                        align: 'center'
                    },
                    {
                        title: '用户名',
                        slot : 'name',
                        width: 80
                    },
                    {
                        title: '密码',
                        key  : 'password'
                    },
                    {
                        title: '年龄',
                        key  : 'age',
                        align: "center"
                    },
                    {
                        title: '出生日期',
                        key  : 'birth',
                        align: "center",
                        width: 120,
                        render(h,params){
                            if(params.row.birth){
                                var date     = new Date(params.row.birth)
                                var dateTime = date.getFullYear()+'-'+(date.getMonth()+1)+'-'+(date.getDate())
                                return h('span',dateTime)
                            }
                        }
                    },
                    {
                        title: '性别',
                        key  : 'gender',
                        align: "center",
                    },
                    {
                        title: '婚姻状况',
                        key  : 'marital',
                        align: "center",
                        width: 90
                    },
                    {
                        title: '月收入',
                        key  : 'salary',
                        align: "right",
                        width: 80
                    },
                    {
                        title  : '个人爱好',
                        key    : 'hobby',
                        tooltip: true,
                        width  : 100,
                        render(h,params){
                            return h('span',params.row.hobby.toString())
                        }
                    },
                    {
                        title  : '用户备注',
                        key    : 'desc',
                        tooltip: true,
                        width  : 100
                    },
                    {
                        title: '操作',
                        slot : 'action',
                        width: 140,
                        align: 'center'
                    }
                ],
                list        : [],
                total       : 0,
                page        : 1,
                rows        : 5,
                modal8      : false,
                ids         : [],
                formValidate: {
                    name    : '',
                    password: '',
                    city    : '',
                    gender  : '',
                    hobby   : [],
                    birth   : '',
                    desc    : '',
                    age     : '',
                    salary  : ''
                },
                ruleValidate: {
                    name: [
                        { required: true, message: '用户名不能为空', trigger: 'blur' }
                    ],
                    password: [
                        { required: true, message: '密码不能为空', trigger: 'blur' }
                    ],
                    marital: [
                        { required: true, message: '婚姻状况不能为空', trigger: 'blur' }
                    ],
                    gender: [
                        { required: true, message: '性别不能为空', trigger: 'change' }
                    ],
                    hobby: [
                        { required: true, type: 'array', min: 1, message: '请选择至少一项爱好', trigger: 'change' },
                    ],
                    birth: [
                        { validator:validate, required: true, message: '请选择出生日期', trigger: 'change' }
                    ],
                    age: [
                        { validator:validate, required: true, message: '年龄不能为空', trigger: 'blur' }
                    ],
                    desc: [
                        { required: true, message: '请输入备注说明', trigger: 'blur' }
                    ]
                }
            }
        },
        methods: {
            setAge(date){
                var a       = new Date();
                var b       = new Date(date);
                var nowdate = moment(a);
                var setdate = moment(b);
                nowdate.diff(setdate,'years');
                if(this.formValidate.birth==''){
                    this.formValidate.age = ''
                }else{
                    this.formValidate.age = nowdate.diff(setdate,'years');
                }
                    this.formValidate.birth = date
            },
            search(name){
                if(name){
                    this.axios({
                        url   : config.dataBaseUrl+'users/search/'+name,
                        method: 'post'
                    }).then(res=>{
                        this.list  = res.data.rows;
                        this.total = res.data.total
                    })
                }else{
                    this.getList()
                }
            },
            close(name){
                this.handleReset (name);
            },
            show (id) {
                if(id){
                    this.axios({
                        url   : config.dataBaseUrl+"users/"+id,
                        method: "get"
                    }).then(res=>{
                        this.modal8       = true
                        this.formValidate = res.data
                    })
                }else{
                    this.modal8 = true
                }
            },
            getSelections(selection){
                var arr = []
                for(var i=0;i<selection.length;i++){
                    arr.push(selection[i]._id)
                }
                this.ids = arr
            },
            cuts () {
                this.$Modal.confirm({
                    title  : '确认对话框',
                    content: `<p>确认删除选中数据?</p>`,
                    onOk   : () => {
                        this.axios({
                            url   : config.dataBaseUrl+"users/removes",
                            method: "post",
                            data  : {
                                ids: this.ids.toString()
                            }
                        }).then(res=>{
                            this.getList()
                        })
                    },
                    onCancel: () => {
                        this.$Message.info('Clicked cancel');
                    }
                })
            },
            remove(id){
                this.$Modal.confirm({
                    title  : '确认对话框',
                    content: `<p>确认删除该条数据?</p>`,
                    onOk   : () => {
                        this.axios({
                            url   : config.dataBaseUrl+"users/"+id,
                            method: "delete",
                        }).then(res=>{
                            this.getList()
                        })
                    },
                    onCancel: () => {
                        this.$Message.info('Clicked cancel');
                    }
                })
            },
            getList(){
                this.axios({
                    url   : config.dataBaseUrl+"users/list",
                    method: "post",
                    data  : {
                        page: this.page,
                        rows: this.rows
                    }
                }).then(res=>{
                    this.list  = res.data.rows;
                    this.total = res.data.total
                })
            },
            addUser(){
                this.show()
            },
            onChangePage(page){
                this.page = page;
                this.getList()
            },
            onPageSizeChange(pageSize){
                this.rows = pageSize;
                this.getList()
            },
            handleSubmit (name) {
                this.$refs[name].validate((valid) => {
                    var id = this.formValidate._id;
                    if (valid) {
                        if(id){
                            this.axios({
                                url   : config.dataBaseUrl+"users/"+id,
                                method: "put",
                                data  : this.formValidate
                            }).then(()=>{
                                this.handleReset (name);
                                this.modal8 = false;
                                this.getList()
                            })
                        }else{
                            id = '';
                            this.axios({
                                url   : config.dataBaseUrl+"users",
                                method: "post",
                                data  : this.formValidate
                            }).then(()=>{
                                this.handleReset (name);
                                this.modal8 = false;
                                this.getList()
                            })
                        }
                    } else {
                        this.$Message.error('Fail!');
                    }
                })
            },
            handleReset (name) {
                this.$refs[name].resetFields();
            }
        },
        mounted(){
            this.getList();
        },
    }
</script>